/*
 * @Author: yangzonglong
 * @Date: 2021-05-07 13:54:51
 * @version: v1.0.0
 * @Descripttion:
 * @LastEditors: yangzonglong
 * @LastEditTime: 2023-02-15 14:52:17
 * @Auditor:
 */
import React, { useState, useCallback, useRef, useEffect } from 'react';
import { PageHeader, Formx, Button, units, history, Tabs } from '@library';
import { FormxRefProps } from '@library/components/formx/interface';
import Qs from 'query-string';
import { Button as AntdButton, Dropdown, Modal } from 'antd';
import { exportJson } from '../../../utils/exportJson';
import FormDesign, { FormDesignRefProps } from '../../../components/formDesign/FormDesign';
import ImportJson from './_ImportJson';
import style from './style.module.scss';
import i18n from "@library/app/i18n";
import { db } from '@library'

const required = true;
const t = window.$app.t;

const formItems = [
  { name: 'formName', required },
  { name: 'formDesc', required },
  { name: 'createdAt', disabled: true },
];

const initialValues = { };

const tabsData = [
  { id: 'base', label: t('baseInfo') },
  { id: 'form', label: t('formDetails') }
];

const DetailsPage = () => {
  const isChange = useRef(false);
  const query = Qs.parseUrl(window.location.href).query;
  const formDesignRef = useRef<FormDesignRefProps>(null);
  const formxRef = useRef<FormxRefProps>(null);
  const [details, setDetails] = useState<any>(initialValues as any);
  const [current, setCurrent] = useState(tabsData[0].id);

  useEffect(() => {
    if (query.id)
      db.getForm(query.id).then((details) => {
        if (typeof details !== 'boolean') {
          setDetails(details);
        }
      });
  }, [query.id]);

  const onValuesChange = useCallback(
    (value, allValue) => {
      isChange.current = true;
    },
    [details]
  );

  const check = useCallback(async () => {
    const formData = await formxRef.current?.validateFields();
    if (!formData) return;

    formDesignRef.current?.getDesign(formData.formName);
  }, []);

  const onSubmit = useCallback(async (content) => {

    const fn = async () => {
      const formData = await formxRef.current?.validateFields();

      const mergeData = { ...formData, content };

      let contentData = content ? JSON.parse(content) : {};

      contentData = contentData.list?.map((item: any) => {
        return {
          key: item.options?.formItemProps?.name || item.id,
          title: item.options?.formItemProps?.label || item.options?.title,
          type: item.type
        };
      }, {});

      mergeData.contentData = JSON.stringify(contentData);

      const result: any = await db.saveForm(mergeData as any);
      console.log('saveForm result', result)

      if (result) {
        isChange.current = false;
        setDetails(prev => ({ ...prev, ...result }));
        units.message.success();
        history.replace('/myform/details?id=' + result.id);
      }
    };

    if (details.id) {
      const res: any = await db.getForm(details.id);
      if (res?.updatedAt.getTime() !== details.updatedAt.getTime()) {
        Modal.confirm({
          title: t('form_tips'),
          cancelText: t('cancel'),
          okText: t('ok'),
          onOk() {
            fn();
          },
          onCancel() {

          }
        });
      } else {
        fn();
      }
    } else {
      fn();
    }


  }, [details.updatedAt, details.id]);

  const exportJsonFn = useCallback(() => {
    formDesignRef.current?.getDesign('GFORM', (design: string) => {
      exportJson('gform.json', design);
    }, true);
  }, []);

  const initGform = useCallback((str: string) => {
    formDesignRef.current?.syncGform(str ? JSON.parse(str).list : []);
  }, []);

  const preview = useCallback(() => {
    // formDesignRef.current?.preview()
    window.open(`${window.location.href.includes('http://localhost') ? '' : '/core/app'}/myform/details/preview?id=` + query.id);
  }, [query.id]);

  const formDesignChange = useCallback(() => (isChange.current = true), []);

  // 对于echarts图表 全局挂载chartsResize方法 撑满区域
  useEffect(() => {
    if (current === tabsData[1].id) {
      (window as any).chartsResize?.forEach((element: Function) => {
        element?.();
      });
    }
  }, [current]);

  // 销毁挂载的chartsResize方法
  useEffect(() => {
    return () => {
      (window as any).chartsResize = null;
    };
  }, []);


  return (
    <>
      <PageHeader
        extra={
          <>
            
            <AntdButton.Group>
              <Button.View disabled={!query?.id} onClick={preview} type="default">
                {t('preview')}
              </Button.View>
              <Button.Download onClick={exportJsonFn} type="default">
                {t('export')}
              </Button.Download>

              <Dropdown overlay={<ImportJson onOk={initGform} />}>
                <AntdButton>...</AntdButton>
              </Dropdown>
            </AntdButton.Group>

            <span className="wingBlank" />
            <Button.Save onClick={check} />
          </>
        }
      />
      <div className='common-block common-flex'>
        <Tabs mode='tabs' tabs={tabsData} curTabId={current} onChange={setCurrent} />
        <div hidden={current === tabsData[1].id}>
          <Formx initialValues={details} ref={formxRef} formItems={formItems} onValuesChange={onValuesChange} />
        </div>
        <div hidden={current === tabsData[0].id} className='common-flex'>
          <div className={style.formDesign}>
            <FormDesign
              onChange={formDesignChange}
              formInfo={{ formDesc: details.formDesc, formName: details.formName }}
              content={details.content}
              ref={formDesignRef}
              onOk={onSubmit}
              formEngine={'GFORM'}
            />
          </div>
        </div>
      </div>
    </>
  );
};

export default DetailsPage